package cn.virens.server.aio;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.App;
import cn.virens.app.AppConfig;
import cn.virens.app.timer.TimedTask;
import cn.virens.server.aio.channel.AioChannel;
import cn.virens.server.aio.channel.AioChannelSimple;

public class AioServerMonitor extends TimedTask {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private Integer period;
	private Integer rtimeout;
	private Integer wtimeout;

	@Override
	public void initialize(AppConfig config) throws Exception {
		this.wtimeout = config.getInteger("aio.monitor.timeout.write");
		this.rtimeout = config.getInteger("aio.monitor.timeout.read");
		this.period = config.getInteger("aio.monitor.timer");
	}

	@Override
	public void destroy() throws Exception {

	}

	@Override
	protected void doRun() throws Exception {
		Set<AioChannel> aaa = App.aio().getChannelAll();
		logger.debug("当前在线连接数:" + aaa.size());

		for (AioChannel aioChannel : App.aio().getChannelAll()) {
			AioChannelSimple channel = (AioChannelSimple) aioChannel;

			if (rtimeout(channel) || wtimeout(channel)) {
				App.aio().unbindUid(channel);
			}
		}
	}

	private boolean rtimeout(AioChannelSimple channel) {
		return timeout(channel.getLastReadTick(), rtimeout);
	}

	private boolean wtimeout(AioChannelSimple channel) {
		return timeout(channel.getLastWriteTick(), wtimeout);
	}

	private static boolean timeout(long tick, long timeout) {
		return tick + timeout < System.currentTimeMillis();
	}

	@Override
	protected Integer period() {
		return period;
	}

}
